import 'package:flutter/material.dart';
import 'package:lovify/models/enums/gender.dart';
import 'package:lovify/widgets/aq_text.dart';

class AqGenderSwitch extends StatefulWidget {
  final void Function(String)? onChanged;
  final Gender? defaultValue;

  const AqGenderSwitch({super.key, this.onChanged, this.defaultValue});

  @override
  AqGenderSwitchState createState() => AqGenderSwitchState();
}

class AqGenderSwitchState extends State<AqGenderSwitch> {
  bool isMale = true;

  static const _maleColor = Color(0xFF3487FF);
  static const _femaleColor = Color(0xFFEC4899);
  static const _defaultColor = Color.fromRGBO(217, 217, 217, 1);
  static const _height = 45.0;

  @override
  void initState() {
    super.initState();
    if (widget.defaultValue != null) {
      isMale = widget.defaultValue == Gender.male;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: _defaultColor,
        borderRadius: BorderRadius.circular(4),
        border: Border.all(color: _defaultColor, width: 2),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          _genderSwitchOption(
            isSelected: isMale,
            icon: Icons.male,
            label: '男',
            onTap: () => _onGenderChanged(true),
            color: _maleColor,
          ),
          _genderSwitchOption(
            isSelected: !isMale,
            icon: Icons.female,
            label: '女',
            onTap: () => _onGenderChanged(false),
            color: _femaleColor,
          ),
        ],
      ),
    );
  }

  void _onGenderChanged(bool male) {
    setState(() {
      isMale = male;
    });

    if (widget.onChanged != null) {
      widget.onChanged!(male ? 'MALE' : 'FEMALE');
    }
  }

  Widget _genderSwitchOption({
    required bool isSelected,
    required IconData icon,
    required String label,
    required VoidCallback onTap,
    required Color color,
  }) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          height: _height,
          decoration: BoxDecoration(
            color: isSelected ? Colors.white : _defaultColor,
            borderRadius: const BorderRadius.all(Radius.circular(4)),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                icon,
                color: isSelected ? color : Colors.black,
              ),
              const SizedBox(width: 8),
              AQText(
                content: label,
                color: isSelected ? color : Colors.black,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
